import { login, logout } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { constantRouterMap } from '@/router'

const user = {
  state: {
    token: getToken(),
    id: '',
    username: '',
    name: '',
    avatar: '',
    // 角色id，目前是一对一的角色关系
    roleId: '',
    routers: constantRouterMap,
    addRouters: [],
    menus: [],
    user: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_ID: (state, id) => {
      state.id = id
    },
    SET_USERNAME: (state, username) => {
      state.username = username
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLEID: (state, role) => {
      state.roleId = role
    },
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = routers
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(username, userInfo.password).then(response => {
          setToken(response.value.token)
          commit('SET_TOKEN', response.value.token)
          commit('SET_USERNAME', username)
          localStorage.setItem('menus', JSON.stringify(response.value.menus))
          commit('SET_MENUS', response.value.menus)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.username).then(response => {
          const data = response.data
          if (data.roleId) {
            commit('SET_ROLEID', data.roleId)
          } else {
            reject('getInfo: role must be a non-null array !')
          }
          commit('SET_ID', data.id)
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLEID', '')
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
